/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.process;

import com.sun.org.apache.regexp.internal.REProgram;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.ejb.EJBAccessException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import server.entity.Admin;
import server.entity.AdminLog;
import server.entity.Category;
import server.entity.Comment;
import server.entity.CreatesContest;
import server.entity.Faq;
import server.entity.ImageContest;
import server.entity.JoinContest;
import server.entity.Photo;
import server.entity.RegisteredUser;
import server.entity.ViewPhoto;
import server.entity.ViewPhotoPK;
import server.entity.Vote;

/**
 *
 * @author Hoang
 */
@Stateless
public class ProcessBean implements ProcessBeanRemote, ProcessBeanLocal {

    @PersistenceContext(unitName = "WebPhotoShare-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    //Hai Process Bean
    public Comment[] getListComment(int photoID) {

        Photo photo = em.find(Photo.class, photoID);
        Collection<Comment> colComments = photo.getCommentCollection();
        Iterator it = colComments.iterator();
        List<Comment> result = new ArrayList<Comment>();
        while (it.hasNext()) {
            Comment comment = (Comment) it.next();
            if (comment.getStatus() == true) {
                result.add(comment);
            }
        }
        Comment[] arrComments = new Comment[result.size()];
        result.toArray(arrComments);
        return arrComments;
    }

    public boolean AddComment(String email, String user, String conntent, int photoid, boolean approved, boolean staus) {
        RegisteredUser registeredUser = em.find(RegisteredUser.class, user);
        Photo photo = em.find(Photo.class, photoid);
        Comment comment = new Comment();

        Date todayD = new Date(System.currentTimeMillis());

        //Khai bao dinh dang ngay thang
        // SimpleDateFormat dayFormat = new SimpleDateFormat("dd/MM/yyyy");


        comment.setCommentDate(todayD);
        comment.setEmail(email);
        comment.setRegisteredUser(registeredUser);
        //  registeredUser.getCommentCollection().add(comment);
        comment.setCommentContent(conntent);
        //   photo.getCommentCollection().add(comment);
        comment.setPhoto(photo);
        comment.setApproved(approved);
        comment.setStatus(staus);
        em.persist(comment);



        return true;
    }

    public boolean CheckDeleteComment(int id) {
        Comment com = em.find(Comment.class, id);
        em.remove(com);
        return true;
    }

    public Comment[] ShowAllComment() {
        Query quert = em.createNamedQuery("Comment.findAll");
        Collection listcomment = quert.getResultList();
        Comment[] result = new Comment[listcomment.size()];
        listcomment.toArray(result);
        return result;
    }

    public boolean CheckUpdateComment(int commentid, String email, String username123, String content123, int photoIDasd, boolean approved, boolean sratus) {

        RegisteredUser registeredUser = em.find(RegisteredUser.class, username123);
        Photo photo = em.find(Photo.class, photoIDasd);
        Date todayD = new Date(System.currentTimeMillis());
        Comment comment = em.find(Comment.class, commentid);
        if (comment.getRegisteredUser().getUsername().equals(username123)) {

            comment.setCommentDate(todayD);
            comment.setEmail(email);

            comment.setRegisteredUser(registeredUser);
            //  registeredUser.getCommentCollection().add(comment);
            comment.setCommentContent(content123);
            //   photo.getCommentCollection().add(comment);
            comment.setPhoto(photo);

            comment.setApproved(approved);
            comment.setStatus(sratus);

            em.persist(comment);
        }
        return true;

    }

    public boolean CheckUpdatecategory(String CollectiId, String Collecname, String description, String ruusername, boolean admin,String Image) throws ObjectNotFoundException {
        Date todayD = new Date(System.currentTimeMillis());

        if (admin == true) {
            Query quety = em.createNamedQuery("Category.findByAdmin");
            quety.setParameter("admin", admin);
            List list = quety.getResultList();

            Category caterory = em.find(Category.class, CollectiId);
            //     System.out.println(CollectiId);
            if (caterory == null) {
                throw new ObjectNotFoundException(CollectiId + " is not exist");
            }
            if (list.contains(caterory)) {

                caterory.setCollectionName(Collecname);
                caterory.setCollectionDescription(description);
                caterory.setDate(todayD);
                caterory.setImage(Image);
                em.persist(caterory);

                return true;
            }
        } else {
            Category care = em.find(Category.class, CollectiId);
            if (care.getRegisteredUser().getUsername().equals(ruusername)) {
                care.setCollectionName(Collecname);
                care.setCollectionDescription(description);
                care.setImage(Image);
                em.persist(care);
            }
        }
        return true;
    }

    public Category[] ShowAdminCategory(String user, boolean admin) {
        if (admin == true) {
            Query quret = em.createNamedQuery("Category.findByAdmin");
            quret.setParameter("admin", admin);
            Collection listAdminCato = quret.getResultList();
            Category[] reuslt = new Category[listAdminCato.size()];
            listAdminCato.toArray(reuslt);
            return reuslt;
        } else {
            RegisteredUser res = em.find(RegisteredUser.class, user);
            List list = (List) res.getCategoryCollection();
            Category[] result = new Category[list.size()];
            list.toArray(result);
            return result;

        }

    }

    public boolean AddFAQ(String question123, String anawers123) {
        Faq faq = new Faq();
        faq.setQuestion(question123);
        faq.setAnswers(anawers123);
        em.persist(faq);
        return true;
    }

    public Faq[] ShowAllfaq() {
        Query query = em.createNamedQuery("Faq.findAll");
        Collection listfaq = query.getResultList();
        Faq[] result = new Faq[listfaq.size()];
        listfaq.toArray(result);
        return result;
    }

    public boolean checkDeletefaq(int faqid) {
        Faq faq = em.find(Faq.class, faqid);
        em.remove(faq);
        return true;
    }

    public boolean CheckUpdateFaq(int idfaq, String question123, String answers123) {
        Faq faq = em.find(Faq.class, idfaq);
        faq.setQuestion(question123);
        faq.setAnswers(answers123);
        em.persist(faq);

        return true;
    }

    public ViewPhoto[] CheckReportViewPhoto(String date123) {
        Query query = em.createNamedQuery("ViewPhoto.findByDate");
        query.setParameter("date", date123);
        Collection listdate = query.getResultList();
        ViewPhoto[] reulst = new ViewPhoto[listdate.size()];
        listdate.toArray(reulst);

        return reulst;
    }

    private Photo[] getTop10byView(ViewPhoto[] array) {
        // ViewPhoto[] bm =array;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length - 1; j++) {
                if (array[i].getPhotoView() < array[j].getPhotoView()) {

                    ViewPhoto bm = new ViewPhoto();
                    bm = array[i];
                    array[i] = array[j];
                    array[j] = bm;
                }
            }
        }
        Photo[] ph = new Photo[10];
        for (int i = 0; i < 10; i++) {
            ph[i] = array[i].getPhoto();
        }
        return ph;
    }

    public List<Photo> reportTop10PhotobyView(String fromdate, String todate) {
        try {
            java.sql.Date fDate = java.sql.Date.valueOf(fromdate);
            java.sql.Date tDate = java.sql.Date.valueOf(todate);
            //fDate.
            Calendar fCalendar = Calendar.getInstance();
            fCalendar.setTime(fDate);
            Calendar tCalendar = Calendar.getInstance();
            tCalendar.setTime(tDate);
            HashMap<Integer, Photo> hm = new HashMap();
            do {
                Photo[] ph = getTop10byView(CheckReportViewPhoto(fCalendar.toString()));
                for (int i = 0; i < ph.length; i++) {
                    if (hm.containsKey(ph[i].getPhotoID())) {
                        //set + view
                        long oldview = hm.get(ph[i].getPhotoID()).getViews();
                        long newview = ph[i].getViews();
                        hm.get(ph[i].getPhotoID()).setViews(oldview + newview);
                    } else {
                        hm.put(new Integer(ph[i].getPhotoID()), ph[i]);
                    }
                }
                fCalendar.add(Calendar.DAY_OF_MONTH, 1);
            } while (fCalendar.before(tCalendar));
            if (fDate.compareTo(tDate) >= 0) {
                //illegal input
            }
            List<Photo> collection = (List<Photo>) hm.values();
            if (collection.size()>10){
                collection.subList(0, 9);
            }
            return collection;
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    public Comment[] SearchLikeComment(int id123) {
        Query quert = em.createNamedQuery("Comment.findByCommentID");
        quert.setParameter("commentID", id123);
        Collection listcomment = quert.getResultList();
        Comment[] result = new Comment[listcomment.size()];
        listcomment.toArray(result);
        return result;


    }

    public boolean AddAdminLog(String action) {
        AdminLog adminlog = new AdminLog();
        adminlog.setAction(action);
        adminlog.setDate(new Date());

        return false;
    }

    public boolean LogAdminlogin() {
        AdminLog adminlog = new AdminLog();
        adminlog.setAction("Login Sucessfull..........");
        Date todayD = new Date(System.currentTimeMillis());
        adminlog.setDate(todayD);
        em.persist(adminlog);
        return true;
    }

    public boolean LogAdminCreateCategory(String Categorynane) {
        AdminLog adminlog = new AdminLog();
        adminlog.setAction(String.format(" Create  New Category : %s", Categorynane));
        Date todayD = new Date(System.currentTimeMillis());
        adminlog.setDate(todayD);
        em.persist(adminlog);
        return true;
    }

    public boolean CheckLogin(String username123, String password123) {
        String checkLogin = "SELECT a FROM Admin a WHERE a.username = :username and  a.password = :password";
        Query quer = em.createQuery(checkLogin);


        quer.setParameter("username", username123);
        quer.setParameter("password", password123);
        List list = quer.getResultList();
        if (list.size() > 0) {
            return true;

        }

        return false;
    }

    public AdminLog[] ShowAllAdminLog() {
        Query query = em.createNamedQuery("AdminLog.findAll");
        Collection list = query.getResultList();
        AdminLog[] reusltd = new AdminLog[list.size()];
        list.toArray(reusltd);

        return reusltd;
    }

    //Tuan process bean
    public boolean login(String name, String pass) {
        String querySql = "SELECT a FROM Admin a WHERE a.username = :username and a.password = :password";
        Query query = em.createQuery(querySql);
        query.setParameter("username", name);
        query.setParameter("password", pass);
        List resuil = query.getResultList();
        if (resuil.size() > 0) {
            return true;
        }
        return false;
    }

    public boolean ChangePassWordAdmin(String name, String OldPass, String NewPass) {

        String querySql = "SELECT a FROM Admin a WHERE a.username = :username and a.password = :password";
        Query query = em.createQuery(querySql);
        query.setParameter("username", name);
        query.setParameter("password", OldPass);
        List resuil = query.getResultList();
        if (resuil.size() > 0) {
            Admin admin = em.find(Admin.class, name);
            admin.setPassword(NewPass);
            persist(admin);
            return true;
        }
        return false;
    }

    public boolean LogUser(String UserName) {
        RegisteredUser user = em.find(RegisteredUser.class, UserName);
        user.setApproved(false);
        persist(user);
        return true;
    }

    public boolean UserUpdate(String username, String firstName, String lastName, String Address, String phone, String email) {
        RegisteredUser user = em.find(RegisteredUser.class, username);
        user.setFirstName(firstName);
        user.setLastName(lastName);


        user.setAddress(Address);
        user.setPhone(phone);
        user.setEmail(email);
        persist(user);
        return true;
    }

    public boolean ChangePassUser(String name, String oldpass, String newpass) {
        String querySql = "SELECT r FROM RegisteredUser r WHERE r.username = :username and r.password = :password";
        Query query = em.createQuery(querySql);
        query.setParameter("username", name);
        query.setParameter("password", oldpass);
        List resuil = query.getResultList();
        if (resuil.size() > 0) {
            RegisteredUser user = em.find(RegisteredUser.class, name);
            user.setPassword(newpass);
            persist(user);
            return true;
        }
        return false;

    }

    public List SearchUserByUserName(String nameSearch) {
        String querySQL = "SELECT r FROM RegisteredUser r WHERE r.username LIKE :username";
        Query query = em.createQuery(querySQL);
        query.setParameter("username", "%" + nameSearch + "%");
        List<RegisteredUser> user = query.getResultList();
        return user;
    }

    public List ListAllUser() {
        Query query = em.createNamedQuery("RegisteredUser.findAll");
        List user = query.getResultList();
        return user;
    }

    public boolean ActiveUser(String name) {
        RegisteredUser user = em.find(RegisteredUser.class, name);
        user.setApproved(true);
        persist(user);
        return true;
    }

    public RegisteredUser OneUser(String name) {
        RegisteredUser user = em.find(RegisteredUser.class, name);
        return user;
    }

    public List reportCommentPhoto(String fromDate, String toDate) {

        Photo photo = null;
        int totalcomment = 0;
        List<TopCommentPhoto> list = new ArrayList<TopCommentPhoto>();
        try {
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date utilFromDate = dateFormat.parse(fromDate);
            java.util.Date utilToDate = dateFormat.parse(toDate);
            Calendar calFromDate = Calendar.getInstance();
            Calendar calToDate = Calendar.getInstance();
            calFromDate.setTimeInMillis(utilFromDate.getTime());
            calToDate.setTimeInMillis(utilToDate.getTime());
            Query query = em.createQuery("SELECT c FROM Comment c WHERE c.commentDate >= :fromDate and c.commentDate <= :toDate");
            query.setParameter("fromDate", utilFromDate);
            query.setParameter("toDate", utilToDate);
            List<Comment> resuilt = query.getResultList();

            for (int i = 0; i < resuilt.size(); i++) {
                photo = resuilt.get(i).getPhoto();
                if (list.isEmpty()) {
                    totalcomment = 1;
                    TopCommentPhoto topcomment = new TopCommentPhoto(photo, totalcomment);

                    list.add(topcomment);
                } else {
                    for (int j = 0; j < list.size(); j++) {
                        totalcomment = 0;
                        if (photo == list.get(j).getPhoto()) {
                            totalcomment = list.get(j).getTotalComment();
                            totalcomment += 1;
                            list.get(j).setTotalComment(totalcomment);
                            break;
                        }
                    }
                    if (totalcomment == 0) {
                        TopCommentPhoto topcomment = new TopCommentPhoto(photo, 1);
                        list.add(topcomment);
                    }
                }
            }
            Collections.sort(list, new CommentPhotoComparator());
            if (list.size() > 10) {
                list.subList(list.size() - 10, list.size());
            } else {
                list.subList(1, list.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }
    //Hoang Process

    public RegisteredUser findUserbyID(String username) {
        RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
        return registeredUser;
    }
    //

    //
    //
    /* Category Process ---------------------------------------------------------------------------------*/
    /*
     * function Name genCollectionID
     * Description: create collection ID
     * input: boolean admin
     * output:String
     * Exception: none
     */
    private String genCollectionID(boolean admin) {

        Query query = em.createNamedQuery("Category.findByAdmin");
        query.setParameter("admin", admin);
        List<Category> lstCategory = query.getResultList();
        String tmp;
        if (lstCategory.isEmpty()) {
            tmp = admin ? "A0001" : "U0001";
            return tmp;
        }
        Category lastCategory = lstCategory.get(lstCategory.size() - 1);
        String lastID = lastCategory.getCollectionID();
        tmp = lastID.substring(1);
        int t = Integer.parseInt(tmp) + 1;
        tmp = "00000" + String.valueOf(t);
        tmp = tmp.substring(tmp.length() - 4);
        tmp = admin ? "A" + tmp : "U" + tmp;
        return tmp;
    }

    /*
     * function Create new Collection Photo
     * Description: Create Collection for admin, user
     * Input: String collectionID,collectionName,Description,username,admin
     * Output:  boolean
     *          True: Create Successful
     *          False:Create Failed
     * Exception:
     *          ObjectNotFoundException
     *          CreateException
     * Object   :
     *          Register user (username!=null && admin=false)
     *          Admin         (username==null && admin=true)
     */
    public boolean createNewCollection(String collectionName, String description, String userName, boolean admin,String Image) throws CreateException, ObjectNotFoundException {
        boolean result = false;
        try {
            Category category = new Category();
            category.setCollectionID(genCollectionID(admin));
            category.setCollectionName(collectionName);
            category.setCollectionDescription(description);
            category.setImage(Image);
            java.util.Date today = new Date();
            java.sql.Date stoday = new java.sql.Date(today.getTime());
            category.setDate(stoday);
            category.setAdmin(admin);
            if (admin == false) {
                RegisteredUser registeredUser = em.find(RegisteredUser.class, userName);
                if (registeredUser == null) {
                    throw new ObjectNotFoundException(userName + " not found");
                }
                category.setRegisteredUser(registeredUser);
            }
            em.persist(category);
            result = true;
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new CreateException("Can not create collection");
        } finally {
            return result;
        }
    }

    //
    public Category[] getListCollection(String user, boolean admin) throws ObjectNotFoundException, RuntimeException {
        try {
            if (admin == true) {
                Query quret = em.createNamedQuery("Category.findByAdmin");
                quret.setParameter("admin", admin);
                Collection listAdminCato = quret.getResultList();
                Category[] reuslt = new Category[listAdminCato.size()];
                listAdminCato.toArray(reuslt);
                return reuslt;
            } else {
                RegisteredUser res = em.find(RegisteredUser.class, user);
                if (res == null) {
                    throw new ObjectNotFoundException(user + "is not found");
                }
                List list = (List) res.getCategoryCollection();
                Category[] result = new Category[list.size()];
                list.toArray(result);
                System.out.println(result.length);
                return result;
            }
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("get List Failed");
        }

    }

    //
    public Category findbyCollectionID(String CollectionID) throws ObjectNotFoundException {
        System.out.println(CollectionID);
        Category category = em.find(Category.class, CollectionID);
        if (category == null) {
            throw new ObjectNotFoundException(CollectionID + " is not found");
        }
        return category;
    }
    //
    //
    /*
     * function name: removeCategory
     * Description  : registered user delete own collection, admin delete empty collection
     * Input        :   String CategoryID, username, admin
     * Output       :  boolean
     *                 true: delete success
     *                 false: delete failed
     * Exception    :
     *                 RemoveException
     *                 ObjectNotFoundException
     * Object       :
     *                 Registered User (username!=null && admin==false)
     *                 Admin           (username==null && admin==true)
     */

    public boolean removeCategory(String CategoryID, String username, boolean admin) throws RemoveException, ObjectNotFoundException {
        boolean result = false;
        try {
            if (admin) {
                Category category = em.find(Category.class, CategoryID);
                if (category == null) {
                    throw new ObjectNotFoundException(CategoryID + " not found");
                }
                Collection<Photo> collectionPhoto = category.getPhotoCollection();
                if (category.getAdmin()) {
                    //admin delete admin collection
                    if (collectionPhoto.isEmpty()) {
                        //delete when collection is empty only
                        em.remove(category);
                        result = true;
                    } else {
                        result = false;
                    }
                }
            } else {
                Category category = em.find(Category.class, CategoryID);
                if (category == null) {
                    throw new ObjectNotFoundException(CategoryID + " not found");
                }
                if (category.getRegisteredUser().getUsername().equals(username)) {
                    //username is the owner of the category and allow to delete
                    em.remove(category);
                    result = true;
                }
            }
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(CategoryID + " not found");
        } catch (Exception ex) {
            throw new RemoveException("Remove failed " + ex.getMessage());
        } finally {
            return result;
        }
    }
    /*
     *
     *
     */

    public boolean Updatecategory(String CollectiId, String Collecname, String description, String ruusername, boolean admin,String Image) throws ObjectNotFoundException {
        if (admin == true) {
            Query quety = em.createNamedQuery("Category.findByAdmin");
            quety.setParameter("admin", admin);
            List list = quety.getResultList();
            System.out.println(CollectiId);
            Category caterory = em.find(Category.class, CollectiId);
            System.out.println("ddddddddddddddd");
            if (caterory == null) {
                
                throw new ObjectNotFoundException(CollectiId + " is not exist");
            }
            if (list.contains(caterory)) {
                caterory.setCollectionName(Collecname);
                caterory.setCollectionDescription(description);
                caterory.setImage(Image);
                em.persist(caterory);
                System.out.println("dsdfefegg");
                return true;
            }
            System.out.println("dfffdf");
        } else {
            Category care = em.find(Category.class, CollectiId);
            if (care.getRegisteredUser().getUsername().equals(ruusername)) {
                care.setCollectionName(Collecname);
                care.setCollectionDescription(description);
                care.setImage(Image);
                em.persist(care);
            }
        }
        return true;
    }
    /*
     * function get Admin 's Collections list
     * Input    :none
     * Output   :Category[] array
     * Exception:
     *          FinderException
     * Object   :
     *          All
     */

    public Category[] getPublicCollection() throws FinderException {
        try {
            Query query = em.createNamedQuery("findByAdmin");
            List<Category> lstCategory = query.getResultList();
            Category[] result = new Category[lstCategory.size()];
            lstCategory.toArray(result);
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new FinderException("Cant get list collection ");
        }
    }
    public boolean isCategoryNameExist(String Catname,String username,boolean admin){
        boolean result=false;
        if (admin){

        }else if (!admin){
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            Collection colCollection = registeredUser.getCategoryCollection();
            Iterator it = colCollection.iterator();
            while (it.hasNext()){
                Category cat = (Category) it.next();
                if (cat.getCollectionName().equalsIgnoreCase(Catname)){
                    result=true;
                    break;
                }
            }
        }
        return result;
    }
    /* End Category Process -----------------------------------------------------------------------------*/

    /* Photo Process ------------------------------------------------------------------------------------*/
    /*
     * function create new use for insert a new image info to database when user upload image
     * input: String photoName,serverFile,description,tag,username,collection
     * output:  true: create successful
     *
     * Exception:
     *
     *          FinderException
     */
    public boolean insertNewPhoto(String photoName, String serverFile, String description, String tag, String username, String collectionID) throws ObjectNotFoundException, CreateException, LimitationException {
        boolean result = false;
        try {
            Photo photo = new Photo();
            // Collection which image will be upload to
            Category category = em.find(Category.class, collectionID);
            System.out.println(collectionID);
            if (category == null) {
                throw new ObjectNotFoundException("Upload Collection is not found");
            }
            //Register user who upload the photo
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            if (registeredUser == null) {
                throw new ObjectNotFoundException("Account is not found");
            }
            // Collection is NOT assigned to admin -> limit 35 photo
            if (!category.getAdmin()) {
                // check the registerUser is owner of the collection
                if (category.getRegisteredUser() != registeredUser) {
                    throw new CreateException(username + "is not the owner of collection");
                }
                //check limitation to 35 photo
                if (category.getPhotoCollection().size() == 35) {
                    throw new LimitationException("Collection is full");
                }
                photo.setStatus(true);
            }else{
                photo.setStatus(false);
            }
            photo.setRegisteredUser(registeredUser);
            photo.setCategory(category);
            photo.setDescriptions(description);
            photo.setUploaddate(new Date());
            photo.setPhotoName(photoName);
            photo.setServerFile(serverFile);
            photo.setTag(tag);
            em.persist(photo);
            result = true;
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (LimitationException ex) {
            throw new LimitationException(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new CreateException("Upload image failed");
        } finally {
            return result;
        }
    }
    public boolean insertNewPhotoAdmin(String photoName, String serverFile, String description, String tag, String username, String collectionID,boolean status) throws ObjectNotFoundException, CreateException, LimitationException {
        boolean result = false;
        try {
            Photo photo = new Photo();
            // Collection which image will be upload to
            Category category = em.find(Category.class, collectionID);
            System.out.println(collectionID);
            if (category == null) {
                throw new ObjectNotFoundException("Upload Collection is not found");
            }
            //Register user who upload the photo
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            if (registeredUser == null) {
                throw new ObjectNotFoundException("Account is not found");
            }
            // Collection is NOT assigned to admin -> limit 35 photo
            if (!category.getAdmin()) {
                // check the registerUser is owner of the collection
                if (category.getRegisteredUser() != registeredUser) {
                    throw new CreateException(username + "is not the owner of collection");
                }
                //check limitation to 35 photo
                
            }
            photo.setRegisteredUser(registeredUser);
            photo.setCategory(category);
            photo.setDescriptions(description);
            photo.setUploaddate(new Date());
            photo.setPhotoName(photoName);
            photo.setServerFile(serverFile);
            photo.setTag(tag);
            photo.setStatus(status);
            em.persist(photo);
            result = true;
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        }  catch (Exception ex) {
            ex.printStackTrace();
            throw new CreateException("Upload image failed");
        } finally {
            return result;
        }
    }
    /*
     * function remove photo for user
     * input:   int photoID
     *          String username
     * output:  boolean
     *  value true: remove success
     *  value false: remove failed
     * Exception:
     *          ObjectNotFoundException
     *          RemoveException
     */

    public Photo getPhotobyID(int photoID) throws ObjectNotFoundException {
        Photo photo = em.find(Photo.class, photoID);
        if (photo == null) {
            throw new ObjectNotFoundException(photoID + "is not available");
        } else {
            return photo;
        }
    }

    public boolean removePhoto(int photoID, String username) throws ObjectNotFoundException, RemoveException {
        //check user permission own the photo first
        boolean result = false;
        try {
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            if (registeredUser == null) {
                throw new ObjectNotFoundException(String.format("%s is not found", username));
            }
            Photo photo = em.find(Photo.class, photoID);
            if (photo == null) {
                throw new ObjectNotFoundException("The photo is not found");
            }
            boolean owner = registeredUser.getPhotoCollection().contains(photo);

            //--
            if (!owner) {
                result = false;
            } else {
                em.remove(photo);
                result = true;
            }
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (Exception ex) {
            throw new RemoveException("Can not remove this photo");
        } finally {
            return result;
        }
    }

    public void viewPhoto(int photoID) {
        Photo photo = em.find(Photo.class, photoID);
        if (photo.getCategory().getAdmin()) {
            Date date = new Date();
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            ViewPhotoPK viewPhotoPK = new ViewPhotoPK(photoID, dateFormat.format(date));
            ViewPhoto viewPhoto = em.find(ViewPhoto.class, viewPhotoPK);
            if (viewPhoto == null) {
                viewPhoto = new ViewPhoto(viewPhotoPK, 1);
            } else {
                viewPhoto.setPhotoView(viewPhoto.getPhotoView() + 1);
            }
        }
        photo.setViews(photo.getViews() + 1);
        em.persist(photo);
    }
    /*
     * function name: getTopViewedPhoto()
     * Description  : return the top image viewed
     */

    public List<Photo> getTopViewedPhoto() {
        Query query = em.createNamedQuery("Photo.findAll");
        List<Photo> lstPhotos = query.getResultList();
        Collections.sort(lstPhotos, new PhotoTotalViewComparator());
        return lstPhotos;
    }
    /*
     * function name: getTopCommentPhoto()
     * Description: return the top list photo comment
     */

    public List<Photo> getTopCommentPhoto() {
        Query query = em.createNamedQuery("Photo.findAll");
        List<Photo> lstPhotos = query.getResultList();
        Collections.sort(lstPhotos, new PhotoTotalCommentComparator());
        return lstPhotos;
    }
    /*
     * function name: getListPhoto()
     * Description  : return the array of photo
     */

    public List<Photo> getListPhoto() {
        Query query = em.createQuery("SELECT p FROM Photo p WHERE p.status = :status");
        query.setParameter("status", true);
        List<Photo> lstPhotos = query.getResultList();
        Collections.reverse(lstPhotos);
        return lstPhotos;
    }

    public List<Photo> getListPhotoByCategory(String catID,String username) throws LimitationException{
        List<Photo> result = new ArrayList<Photo>();
        if (catID.charAt(0)=='A'){
            Category cat = em.find(Category.class, catID);
            System.out.println(cat.getPhotoCollection().size());
            result = (List<Photo>) cat.getPhotoCollection();
        }else if (catID.charAt(0)=='U'){
            //check owner first
            Category cat = em.find(Category.class, catID);
            System.out.println(cat.getPhotoCollection().size());
            if (cat.getRegisteredUser().getUsername().equals(username)){
                //allow
                result =(List<Photo>) cat.getPhotoCollection();
            }else{
                throw new LimitationException("Limit access");
            }
        }
        return result;
    }

    public Photo searchbyID(int photoID) {
        Photo photo = em.find(Photo.class, photoID);
        return photo;
    }
    public List<Photo> searchPhotobyName(String name){
        Query query = em.createQuery("SELECT p FROM Photo p WHERE p.photoName like :photoName");
        query.setParameter("photoName", "%"+name+"%");
        List<Photo> lstPhoto = query.getResultList();
        return lstPhoto;
    }
    public List<Photo> searchMyPhoto(String photoname,String username){
        RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
        Collection<Photo> lstMyPhoto = registeredUser.getPhotoCollection();
        List<Photo> result = new ArrayList<Photo>();
        Iterator it = lstMyPhoto.iterator();
        while (it.hasNext()){
            Photo photo = (Photo) it.next();
            if (photo.getPhotoName().contains(photoname)){
                result.add(photo);
            }
        }
        return result;
    }
    public List<Photo> searchMyPhotoInCategory(String category,String username,String imagename) throws LimitationException{
        Category cat = em.find(Category.class, category);
        if (cat.getRegisteredUser().getUsername().equals(username)){
            List<Photo> colPhoto = (List<Photo>) cat.getPhotoCollection();
            return colPhoto;
        }else{
            throw new LimitationException("Permission denied");
        }
    }
    public boolean removePhoto(String username,int photoID) throws LimitationException{
        boolean result =false;
        RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
        Photo photo = em.find(Photo.class, photoID);
        if (registeredUser.getPhotoCollection().contains(photo)){
            //allow
            em.remove(photo);
            result=true;
        }else{
            throw new LimitationException(username+" have not permision delete " + photo.getPhotoName());
        }
        return result;
    }
    /*
     * function update photo for user
     * input:   int photoID
     *          String username
     * output:  boolean
     *  value true: remove success
     *  value false: remove failed
     * Exception:
     *          FinderException
     */

    public boolean updateImage(String username, int photoID, String Descriptions, String tag) throws ObjectNotFoundException, EJBAccessException, RuntimeException {
        boolean result = false;
        try {
            Photo photo = em.find(Photo.class, photoID);
            if (photo == null) {
                throw new ObjectNotFoundException(photoID + "is not valid");
            }
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            if (registeredUser == null) {
                throw new ObjectNotFoundException(username + " is not valid");
            }
            if (!registeredUser.getApproved()) {
                throw new EJBAccessException(username + " is disabled");
            }
            if (photo.getRegisteredUser() != registeredUser) {
                throw new EJBAccessException("Owner permission");
            }
            photo.setDescriptions(Descriptions);
            photo.setTag(tag);
            em.persist(photo);
            result = true;
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (EJBAccessException ex) {
            throw new EJBAccessException(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("Update failed");
        } finally {
            return result;
        }
    }

    public void downloadPhoto(int photoID) {
        Photo photo = em.find(Photo.class, photoID);
        photo.setDownloads(photo.getDownloads() + 1);
        em.persist(photo);
    }
    /*End photo process -----------------------------------------------------------------------------------*/

    /*Registered User process -----------------------------------------------------------------------------*/
    /*
     * function checkLogin
     * Description: check Login user
     * Input :  string username
     *          string password
     * Output: int
     *          value -1: wrong username or password
     *          value  0: Registered User but not active
     *          value  1: Registered User active
     * Exception:
     *  ObjectNotFoundException
     */
    public boolean checkLogin(String username, String password) throws ObjectNotFoundException, RuntimeException {
        try {
            RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
            if (registeredUser == null) {
                throw new ObjectNotFoundException(username + " is not valid");
            }
            if (registeredUser.getPassword().equals(password)) {
                if (registeredUser.getApproved() == true) {
                    return true;
                }
            }
            return false;
        } catch (ObjectNotFoundException ex) {
            throw new ObjectNotFoundException(ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("Check Login failed");
        }
    }

    public String getName(String username) {
        RegisteredUser registeredUser = em.find(RegisteredUser.class, username);
        return registeredUser.getFirstName() + " " + registeredUser.getLastName();
    }


    /*End Registered User Process -------------------------------------------------------------------------*/

    /*
     * Admin View History
     *
     */
    public AdminLog[] listHistory() {
        Query query = em.createNamedQuery("AdminLog.findAll");
        Collection<AdminLog> colAdminLogs = query.getResultList();
        AdminLog[] arrAdminLogs = new AdminLog[colAdminLogs.size()];
        colAdminLogs.toArray(arrAdminLogs);
        return arrAdminLogs;
    }

    public AdminLog[] filterHistory(java.sql.Date fromdate, java.sql.Date todate) {
        Query query = em.createNamedQuery("AdminLog.filterByDate");
        Collection<AdminLog> colAdminLogs = query.getResultList();
        AdminLog[] arrAdminLogs = new AdminLog[colAdminLogs.size()];
        colAdminLogs.toArray(arrAdminLogs);
        return arrAdminLogs;
    }

    /*
     **************************************************************************************************
     * Report Top 10 Image View                                                                       *
     * ************************************************************************************************
     */
    /*
     * function TopImageView(String date)
     * Description: get the top list Photo view by date
     * Input:
     *          String fromDate , toDate;
     * Output:
     *          Array ViewPhoto[]
     *
     */
    private ViewPhoto[] TopImageView(String date) {
        Query query = em.createNamedQuery("ViewPhoto.findByDate");
        query.setParameter("date", date);
        List<ViewPhoto> colViewPhotos = query.getResultList();
        Collections.sort(colViewPhotos, new PhotoViewComparator());
        ViewPhoto[] arrViewPhotos = new ViewPhoto[colViewPhotos.size()];
        colViewPhotos.toArray(arrViewPhotos);
        return arrViewPhotos;
    }

    /*
     * function reportTop10ImageView(String fromDate, String toDate)
     * Description: get the top 10 list photo view date by date
     * Input:
     *          String fromDate
     *          String toDate
     * Output:
     *          Array ImageViewReport[]
     * Exception:
     *          none
     */
    public List<ImageViewReport> reportTop10ImageView(String fromDate, String toDate) {
        try {
            //convert String  - to calendar date
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date utilFromDate = dateFormat.parse(fromDate);
            java.util.Date utilToDate = dateFormat.parse(toDate);
            Calendar calFromDate = Calendar.getInstance();
            Calendar calToDate = Calendar.getInstance();
            calFromDate.setTimeInMillis(utilFromDate.getTime());
            calToDate.setTimeInMillis(utilToDate.getTime());
            HashMap<Integer, ImageViewReport> hashMap = new HashMap<Integer, ImageViewReport>();
            ViewPhoto[] vp;
            do {
                vp = TopImageView(dateFormat.format(calFromDate.getTime()));
                for (int i = 0; i < vp.length; i++) {
                    if (hashMap.containsKey(vp[i].getPhoto().getPhotoID())) {
                        long oldview = hashMap.get(vp[i].getPhoto().getPhotoID()).getTotalView();
                        long newview = vp[i].getPhotoView();
                        hashMap.get(vp[i].getPhoto().getPhotoID()).setTotalView(oldview + newview);
                    } else {
                        ImageViewReport imageViewReport = new ImageViewReport(vp[i].getPhoto(), fromDate, toDate, (long) vp[i].getPhotoView());
                        hashMap.put(new Integer(vp[i].getPhoto().getPhotoID()), imageViewReport);
                    }
                }
                calFromDate.add(Calendar.DAY_OF_MONTH, 1);
            } while (!calFromDate.after(calToDate));
            List<ImageViewReport> lstImageViewReports = new ArrayList<ImageViewReport>(hashMap.values());
            Collections.sort(lstImageViewReports, new PhotoViewReportComparator());
            if (lstImageViewReports.size() > 10) {
                lstImageViewReports.subList(0, 9);
            }
            return lstImageViewReports;
        } catch (ParseException ex) {
            Logger.getLogger(ProcessBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex.getMessage());
        }
    }
    /*
     *******************************************************************************************************
     * Report Top 10 user upload image                                                                     *
     *******************************************************************************************************
     */
    /*
     * Function Name: topUserupload
     * Description: get the top list User upload by date
     * Input : Calendar date;
     * Output: Array UserUploadImageReport
     * Exception:none
     */

    private UserUploadImageReport[] topUserupload(Calendar date) {
        Query query = em.createNamedQuery("Photo.findByUploaddate");
        query.setParameter("uploaddate", date.getTime());
        List<Photo> lstPhotos = query.getResultList();
        Iterator it = lstPhotos.iterator();
        HashMap<String, UserUploadImageReport> hashmap = new HashMap<String, UserUploadImageReport>();
        while (it.hasNext()) {
            Photo photo = (Photo) it.next();
            if (hashmap.containsKey(photo.getRegisteredUser().getUsername())) {
                hashmap.get(photo.getRegisteredUser().getUsername()).count();
            } else {
                UserUploadImageReport userUploadImageReport = new UserUploadImageReport(photo.getRegisteredUser(), date.getTime().toString(), date.getTime().toString(), 1);
                hashmap.put(photo.getRegisteredUser().getUsername(), userUploadImageReport);
            }
        }
        List<UserUploadImageReport> lstUserUploadImageReports = new ArrayList<UserUploadImageReport>(hashmap.values());
        Collections.sort(lstUserUploadImageReports, new UserUploadImageReportComparator());
        UserUploadImageReport[] arrayUserUploadImageReports = new UserUploadImageReport[lstUserUploadImageReports.size()];
        lstUserUploadImageReports.toArray(arrayUserUploadImageReports);
        return arrayUserUploadImageReports;
    }
    /*
     * Function Name: reportTop10UserUpload
     * Description: get the top 10 User upload from date to date
     * Input : String fromdate, todate
     * Output: Array UserUploadImageReport
     * Exception:none
     */

    public List<UserUploadImageReport> reportTop10UserUpload(String fromDate, String toDate) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date utilFromDate = dateFormat.parse(fromDate);
            java.util.Date utilToDate = dateFormat.parse(toDate);
            Calendar calFromDate = Calendar.getInstance();
            Calendar calToDate = Calendar.getInstance();
            calFromDate.setTimeInMillis(utilFromDate.getTime());
            calToDate.setTimeInMillis(utilToDate.getTime());
            HashMap<RegisteredUser, UserUploadImageReport> hashmap = new HashMap<RegisteredUser, UserUploadImageReport>();
            System.out.println("test");
            do {
                UserUploadImageReport[] arrayUserUploadImageReports = topUserupload(calFromDate);
                for (int i = 0; i < arrayUserUploadImageReports.length; i++) {
                    if (hashmap.containsKey(arrayUserUploadImageReports[i].getRegisteredUser())) {
                        int oldvalue = hashmap.get(arrayUserUploadImageReports[i].getRegisteredUser()).getQuantity();
                        int newvalue = arrayUserUploadImageReports[i].getQuantity();
                        hashmap.get(arrayUserUploadImageReports[i].getRegisteredUser()).setQuantity(oldvalue + newvalue);
                    } else {
                        UserUploadImageReport userUploadImageReport = new UserUploadImageReport(arrayUserUploadImageReports[i].getRegisteredUser(), fromDate, toDate, arrayUserUploadImageReports[i].getQuantity());
                        hashmap.put(arrayUserUploadImageReports[i].getRegisteredUser(), userUploadImageReport);
                    }
                }
                calFromDate.add(Calendar.DAY_OF_MONTH, 1);
            } while (!calFromDate.after(calToDate));
            List<UserUploadImageReport> lstUserUploadImageReports = new ArrayList<UserUploadImageReport>(hashmap.values());
            Collections.sort(lstUserUploadImageReports, new UserUploadImageReportComparator());
            if (lstUserUploadImageReports.size() > 10) {
                lstUserUploadImageReports.subList(0, 10);
            }
            return lstUserUploadImageReports;
        } catch (ParseException ex) {
            Logger.getLogger(ProcessBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex.getMessage());
        }
    }

    //tri
//Create contest
    public Boolean insertContest(String name, String content, String requirement, String formDate, String toDate, boolean status) {
        try {
            CreatesContest creContest = new CreatesContest();
            // synchronous Bean
            creContest.setNameContest(name);
            creContest.setContentContest(content);
            creContest.setReqContest(requirement);
            creContest.setFromDate(formDate);
            creContest.setToDate(toDate);
            creContest.setStatus(status);
            //insert database
            persist(creContest);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//View All Contest
    public List viewAllContest() {
        try {
            Query query = em.createNamedQuery("CreatesContest.findAll");
            List result = query.getResultList();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//Update Contest

    public Boolean updateContest(int id, String name, String content, String fromDate, String toDate, boolean status) {
        CreatesContest cc = em.find(CreatesContest.class, id);
        cc.setNameContest(name);
        cc.setContentContest(content);
        cc.setFromDate(fromDate);
        cc.setToDate(toDate);
        cc.setStatus(status);
        persist(cc);
        return true;
    }
//View Registry Contest

    public List viewRegContest() {
        try {
            Query query = em.createNamedQuery("CreatesContest.findByStatus");
            query.setParameter("status", true);
            List result = query.getResultList();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //Registry Contests

    public Boolean registryContest(boolean regStatus, int idContest, String username) {
        try {
            System.out.println(username);
            CreatesContest cc = em.find(CreatesContest.class, idContest);
            RegisteredUser ru = em.find(RegisteredUser.class, username);
            System.out.println(ru.getUsername());
            String sql = "SELECT j FROM JoinContest j WHERE j.registeredUser = :registeredUser AND j.createsContest = :createsContest";
            Query query = em.createQuery(sql);
            query.setParameter("registeredUser", ru);
            query.setParameter("createsContest", cc);
            boolean result = false;
            try {
                Object check = query.getSingleResult();
                boolean status = cc.getStatus();

            } catch (NoResultException nre) {
                JoinContest jc = new JoinContest();
                jc.setRegStatus(regStatus);
                jc.setRegisteredUser(ru);
                jc.setCreatesContest(cc);
                persist(jc);
                result = true;
            }
//            if (status) {
//                if (check == null) {
//                    System.out.println("Register");
//                    JoinContest jc = new JoinContest();
//                    jc.setRegStatus(regStatus);
//                    jc.setRegisteredUser(ru);
//                    jc.setCreatesContest(cc);
//                    persist(jc);
//                    result = true;
//                }
//                //registered
//            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
//View All Image of Contest

    public List ViewAllImage(int idContest) {
        try {
            Query q = em.createNamedQuery("ImageContest.findByIdContest");
            q.setParameter("idContest", idContest);
            List result = q.getResultList();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
// View details of user's image

    public List searchImageOfUser(String username, int idContest) {

        String sql = "SELECT i FROM ImageContest i WHERE i.idContest = :idContest AND i.joinContest = :joinContest";
        Query query = em.createQuery(sql);
        query.setParameter("idContest", idContest);
        query.setParameter("joinContest", username);
        List result = query.getResultList();
        return result;
    }

//Vote
    public Boolean vote(String username, int idImgContest, int mark, String voteComment, java.sql.Date voteDate) {
        try {
            RegisteredUser user = em.find(RegisteredUser.class, username);
            ImageContest ic = em.find(ImageContest.class, idImgContest);


//            String sql = "SELECT j FROM JoinContest j WHERE j.registeredUser = :registeredUser";
//            Query query = em.createQuery(sql);
//            query.setParameter("registeredUser", user);
//            Object object = query.getSingleResult();
            boolean test = false;
            if (!username.equals(ic.getJoinContest().getRegisteredUser().getUsername())) {
                Vote vote = new Vote();
                vote.setMark(mark);
                vote.setVoteComment(voteComment);
                vote.setImageContest(ic);
                vote.setRegisteredUser(user);
                vote.setVoteDate(voteDate);
                persist(vote);
                test = true;
            }
            return test;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

// View Upload
    public List viewUpload(String username, int idContest) {
        RegisteredUser ru = em.find(RegisteredUser.class, username);
        CreatesContest cc = em.find(CreatesContest.class, idContest);

        String sql = "SELECT j FROM JoinContest j WHERE j.regStatus = :regStatus AND j.registeredUser = :registeredUser AND j.createsContest = :createsContest";
        Query query = em.createQuery(sql);
        query.setParameter("regStatus", true);
        query.setParameter("registeredUser", ru);
        query.setParameter("createsContest", cc);
        List result = query.getResultList();
        return result;
    }

//Upload Image
    public Boolean uploadImage(String infoImage, String image, String date, String username, int idContest) {
        try {
            RegisteredUser regName = em.find(RegisteredUser.class, username);
            CreatesContest idCon = em.find(CreatesContest.class, idContest);

            String sql = "SELECT j FROM JoinContest j WHERE j.registeredUser = :registeredUser AND j.createsContest = :createsContest AND j.regStatus = :regStatus";
            Query q = em.createQuery(sql);
            q.setParameter("registeredUser", regName);
            q.setParameter("createsContest", idCon);
            q.setParameter("regStatus", true);
            JoinContest id = (JoinContest) q.getSingleResult();
            int idRegUser = id.getIdRegUser();
            JoinContest jc = em.find(JoinContest.class, idRegUser);
            int object = jc.getImageContestCollection().size();

            boolean test = false;
            if (object == 0) {
                ImageContest imageContest = new ImageContest();
                imageContest.setInfoImage(infoImage);
                imageContest.setImage(image);
                imageContest.setDate(date);
                imageContest.setJoinContest(jc);
                imageContest.setIdContest((Integer) jc.getCreatesContest().getIdContest());
                persist(imageContest);
                test = true;
            }
            return test;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//View Vote
    public List viewVote(String username, int idContest) {
        try {
            RegisteredUser user = em.find(RegisteredUser.class, username);
            CreatesContest contest = em.find(CreatesContest.class, idContest);

            String sql = "SELECT v FROM JoinContest v WHERE v.registeredUser = :registeredUser AND v.createsContest = :createsContest";
            Query joinContest = em.createQuery(sql);
            joinContest.setParameter("registeredUser", user);
            joinContest.setParameter("createsContest", contest);
            JoinContest joinObj = (JoinContest) joinContest.getSingleResult();
            System.out.println(joinObj);

            String sqlImg = "SELECT i FROM ImageContest i WHERE i.joinContest = :joinContest";
            Query imageContest = em.createQuery(sqlImg);
            imageContest.setParameter("joinContest", joinObj);
            //   imageContest.setParameter("idContest", joinObj.getCreatesContest().getIdContest());
            List<ImageContest> image = (List<ImageContest>) imageContest.getResultList();
            System.out.println(image);

            List result = null;
            if (image.size() == 1) {
                String sqlView = "SELECT v FROM Vote v WHERE v.imageContest = :imageContest";
                Query view = em.createQuery(sqlView);
                view.setParameter("imageContest", image);
                result = view.getResultList();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//Create Report

    public List createReport(int idContest) {
        try {
            Query query = em.createNamedQuery("CreatesContest.findByIDContest");
            query.setParameter("iDContest", idContest);
            List result = query.getResultList();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public server.entity.Comment[] SearchCommentID(int photoid) {




        return null;
    }

    public server.entity.Comment[] businessMethod(boolean dasdsa) {
        Query quert = em.createNamedQuery("Comment.findByStatus");
        quert.setParameter("status", dasdsa);
        Collection listcomment = quert.getResultList();
        Comment[] result = new Comment[listcomment.size()];
        listcomment.toArray(result);
        return result;

    }

    public boolean CheckUppdasd(String id, String sstus) {
        return false;
    }
    public List reportTopContest(java.sql.Date fromDate, java.sql.Date toDate, int idContest) {
        Query query = em.createNamedQuery("ImageContest.findByIdContest");
        query.setParameter("idContest", idContest);
        List<ImageContest> imageList = query.getResultList();
        List lsttop = new ArrayList();
        CreatesContest cc = em.find(CreatesContest.class, idContest);

        for (int i = 0; i < imageList.size(); i++) {
            String sql = "SELECT v FROM Vote v WHERE v.voteDate >= :fromDate AND v.voteDate <= :toDate AND v.imageContest = :imageContest";
            Query query1 = em.createQuery(sql);
            query1.setParameter("fromDate", fromDate);
            query1.setParameter("toDate", toDate);
            query1.setParameter("imageContest", imageList.get(i));
            List<Vote> dateList = query1.getResultList();
            //List<Vote> voteList = (List<Vote>) imageList.get(i).getVoteCollection();
            int totalmark = 0;
            Date expFromDate = null;
            Date expToDate = null;
//            for (int j = 0; j < voteList.size(); j++) {
//                totalmark += voteList.get(j).getMark();
//            }
//            ReportTopContest rp = new ReportTopContest(imageList.get(i).getIdContest(), totalmark);
//            lsttop.add(rp);
            Date tempDate = dateList.get(0).getVoteDate();
            for (int j = 0; j < dateList.size(); j++) {
                totalmark += dateList.get(j).getMark();
                if (tempDate.compareTo(dateList.get(j).getVoteDate()) == 0) {
                    expFromDate = dateList.get(j).getVoteDate();
                    //   System.out.println(expFromDate);
                } else if (tempDate.compareTo(dateList.get(j).getVoteDate()) > 0) {
                    expFromDate = dateList.get(j).getVoteDate();
                    System.out.println(expFromDate);
                }else if (tempDate.compareTo(dateList.get(j).getVoteDate()) < 0) {
                    expToDate = dateList.get(j).getVoteDate();
                    System.out.println(expFromDate);
                }
            }
            ReportTopContest rp = new ReportTopContest(cc, imageList.get(i), totalmark, expFromDate, expToDate);

            lsttop.add(rp);
        }
        Collections.sort(lsttop, new TopContestComparator());
        return lsttop;
    }

    public List listphotobyCategoryID(String categoryID) {
        List<Photo> lstPhotos=null;
        try {
            Category category = em.find(Category.class, categoryID);
            lstPhotos = (List<Photo>) category.getPhotoCollection();
            System.out.println(lstPhotos.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstPhotos;
    }

    public boolean activeStatusPhoto(String id) {
        int ktid = 0;
        try {
            ktid = Integer.parseInt(id);
        } catch (Exception e) {
        }
        Photo photo = em.find(Photo.class, ktid);
        photo.setStatus(true);
        persist(photo);
        return true;
    }
    public boolean logStatusPhoto(String id) {
        int ktid = 0;
        try {
            ktid = Integer.parseInt(id);
        } catch (Exception e) {
        }
        Photo photo = em.find(Photo.class,ktid);
        photo.setStatus(false);
        persist(photo);
        return true;
    }

}
//Tri

